use crate::common::{Response, WxErr};
use bytes::Bytes;
use reqwest::Client;

use super::req::{qr_code_req::QrCodeReq, unlimit_req::UnlimitReq};

pub async fn get_qr_code<T>(token: &T, req: &QrCodeReq) -> Result<Response<Bytes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = format!(
        "https://api.weixin.qq.com/wxa/getwxacode?access_token={}",
        token.as_ref()
    );
    let client = Client::new();
    let result = client.post(url).json(req).send().await?;
    if result.status().is_success() {
        let result = result.bytes().await?;
        Ok(Response::Ok(result))
    } else {
        let result = result.json::<WxErr>().await?;
        Ok(Response::Err(result))
    }
}

pub async fn get_wxacode_unlimit<T>(
    token: &T,
    req: &UnlimitReq,
) -> Result<Response<Bytes>, reqwest::Error>
where
    T: AsRef<str>,
{
    let url = format!(
        "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={}",
        token.as_ref()
    );
    let client = Client::new();
    let res = client.post(url).json(req).send().await?;
    if res.status().is_success() {
        Ok(Response::Ok(res.bytes().await?))
    } else {
        Ok(Response::Err(res.json().await?))
    }
}
